package io.gitee.crud.util;

import io.gitee.crud.model.dto.DemoUserDTO;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Method;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

public class TreeUtils {

    public static List<DemoUserDTO> findWithRecursive(DemoUserDTO node, String properties, String value) {
        List<DemoUserDTO> list = new LinkedList<>();
        recursive(node, properties, value, list);
        return list;
    }

    private static <T> void recursive(DemoUserDTO node, String properties, String value, List<DemoUserDTO> resultList) {
        if (node == null) {
            return;
        }
        String parseValue;
        try {
            Class<?> clazz = node.getClass();
            Method getMethod = clazz.getMethod("get" + properties);
            parseValue = (String)getMethod.invoke(node);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (Objects.equals(value, parseValue)) {
            resultList.add(node);
        }
        if (!CollectionUtils.isEmpty(node.getUserList())) {
            node.getUserList().forEach(
                    child -> recursive(child, properties, value, resultList));
        }
    }
}
